/**
 * Created with IntelliJ IEDA.
 * Description:
 * User:86186
 * Date:2022-09-23
 * Time:21:48
 */

//class ListNode {
//    public int val;
//    public ListNode next;
//
//    public ListNode(int val) {
//        this.val = val;
//    }
//}

/**
 * 力扣707:设计链表
 */

class MyLinkedList {
    //实时记录当前链表的节点的个数
    public int UseSized;
    //单链表
    public ListNode head;

    public MyLinkedList() {
        UseSized = 0;
        head = new ListNode(0);
    }
    //获取对应下标的值
    public int get(int index) {
        if (index < 0 || index >= UseSized) {
            return -1;
        }
        ListNode cur = head;
        for (int i = 0; i <= index; i++) {
            cur = cur.next;
        }
        return cur.val;
    }

    //头插
    public void addAtHead(int val) {
        addAtIndex(0, val);
    }

    //尾插
    public void addAtTail(int val) {
        addAtIndex(UseSized, val);
    }

    //在对应下标之前添加节点
    public void addAtIndex(int index, int val) {
        if (index > UseSized) {
            return;
        }
        index = Math.max(0, index);
        UseSized++;
        ListNode pred = head;
        for (int i = 0; i < index; i++) {
            pred = pred.next;
        }
        ListNode toAdd = new ListNode(val);
        toAdd.next = pred.next;
        pred.next = toAdd;
    }

    //删除对应节点
    public void deleteAtIndex(int index) {
        if (index < 0 || index >= UseSized) {
            return;
        }
        ListNode pre = head;
        for (int i = 0; i < index; i++) {
            pre = pre.next;
        }
        pre.next = pre.next.next;
        UseSized--;
    }
}
public class MyLinkedList1 {
    public static void main(String[] args) {

    }
}
